<?php

namespace app\api\controller;

use think\Db;
use think\Request;
use think\Controller;
use app\api\model\User;
use think\exception\HttpResponseException;

class Session extends Controller
{
    protected $beforeActionList = [
        'CheckLogin' =>  ['only'=>'delete']
    ];


    protected function CheckLogin()
    {
        if (!session('user.id')) {
            throw new HttpResponseException(json(["code"=>2,"msg"=>"未登录","data"=>null]));
        }
    }

    /**
     * 显示资源列表
     * 测试用户是否登陆
     * @return \think\Response
     */
    public function index()
    {
        if (session('user.id')) {
            return json(["code"=>0,"msg"=>"已登陆","data"=>session('user')]);
        } else {
            return json(["code"=>1,"msg"=>"未登录","data"=>null]);
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     * 创建Session（登陆）
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        if (!empty($request->post('name')) && !empty($request->post('password'))) {
            $user = Db::table('user')->where('name',$request->post('name'))->where('password',$request->post('password'))->find();
            if ($user) {
                unset($user['password']);//不输出密码信息
                session('user', $user);
                return json(["code"=>0,"msg"=>"登陆成功","data"=>$user]);
            } else {
                return json(["code"=>1,"msg"=>"登陆失败","data"=>null]);
            }
        }
        return json(["code"=>4,"msg"=>"参数错误","data"=>null]);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     * 退出登录
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if ($id == session('user.id')) {
            session('user', null);
            return json(["code"=>0,"msg"=>"退出登陆","data"=>null]);
        }
        return json(["code"=>3,"msg"=>"无法退出登录","data"=>null]);
    }
}
